/**
 * @Project Name:blog-business-service
 * @Package Name:cn.hoofungson.blog.business.service.provider.service.user
 * @Since JDK 1.8
 */

package cn.hoofungson.blog.business.service.provider.service.user;

import cn.hoofungson.blog.business.service.interfaces.domain.dto.user.UserDTO;
import cn.hoofungson.blog.business.service.provider.converter.user.UserConverter;
import cn.hoofungson.blog.business.service.provider.model.entity.user.UserPO;
import cn.hoofungson.blog.business.service.provider.repositories.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @Description: UserService
 * @Author 胡松 hoofungson@163.com
 * @Date 2020-03-25 8:30
 * @Version V1.0
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 保存或更新
     *
     * @param userDTO
     **/
    public void save(UserDTO userDTO) {
        if (null == userDTO) {
            return;
        }
        UserPO userPO = new UserPO();
        UserConverter.convert(userDTO, userPO);
        this.userRepository.save(userPO);
    }

    /**
     * 根据ID删除
     *
     * @param id
     **/
    public void deleteById(Long id) {
        this.userRepository.deleteById(id);
    }

    /**
     * 根据所传实体删除
     *
     * @param userDTO
     **/
    public void delete(UserDTO userDTO) {
        if (null == userDTO) {
            return;
        }
        UserPO userPO = new UserPO();
        UserConverter.convert(userDTO, userPO);
        this.userRepository.delete(userPO);
    }

    /**
     * 删除所有
     **/
    public void deleteAll() {
        this.userRepository.deleteAll();
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     **/
    public UserDTO get(Long id) {
        Optional<UserPO> optional = this.userRepository.findById(id);
        if (!optional.isPresent()) {
            return null;
        }
        UserPO userPO = optional.get();
        UserDTO userDTO = new UserDTO();
        UserConverter.convert(userPO, userDTO);
        return userDTO;
    }

    /**
     * 根据用户名查询
     *
     * @param username
     * @return
     **/
    public UserDTO getByUsername(String username) {
        UserPO userPO = this.userRepository.getByUsername(username);
        UserDTO userDTO = new UserDTO();
        UserConverter.convert(userPO, userDTO);
        return userDTO;
    }
}
